/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sahd.broker.proxys;

import sahd.broker.iONetMessageManager.IONetMessageManager;
import java.io.IOException;
import java.net.*;
import java.net.UnknownHostException;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Omega Zero
 */
public class ProxyClient {

    private final String brokerIpAddres = "127.0.0.1";
    private final int SERVICE_RESPONSE_PORT=4444;
    private IONetMessageManager ioNetMessageManager;
    private ServiceResponseManager serviceResponseManager;

    private static ProxyClient instance;

    public static ProxyClient getInstance(Observer clientReceiver, int outPort, int entryPort,
                int serviceResponsePort,String initialReceiverIpAddres) throws UnknownHostException, SocketException{
        if(instance==null){
            instance= new ProxyClient(clientReceiver, outPort, entryPort, serviceResponsePort,
                    initialReceiverIpAddres);
        }
        return instance;
    }
    
    public static ProxyClient getInstance() throws ProxyClientNotInstantiatedException{
        if(instance!=null){
            return instance;
        }
        throw new ProxyClientNotInstantiatedException();
    }

    private ProxyClient(Observer clientReceiver, int outPort, int entryPort,
            int serviceResponsePort,String initReceiverIpAddres) throws UnknownHostException,
            SocketException{
        try {
            ioNetMessageManager = new IONetMessageManager(clientReceiver, outPort,
                    entryPort, initReceiverIpAddres);
            serviceResponseManager = ServiceResponseManager.getInstance(clientReceiver,
                    SERVICE_RESPONSE_PORT,serviceResponsePort, initReceiverIpAddres);

        } catch (UnknownHostException ex) {
            Logger.getLogger(ProxyClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ProxyClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void shipMessage(Object message, int protocol) throws IOException{
        ioNetMessageManager.shipMessage(message, protocol);
    }

    public void setBrokerIpAddres(String brokerIpAddress) throws UnknownHostException, IOException{
        this.ioNetMessageManager.setReceiverIpAddres(brokerIpAddres);
    }

    public void setOutPort(int outPort){
        this.ioNetMessageManager.setOutPort(outPort);
    }
    public void setEntryPort(int entryPort){
        this.ioNetMessageManager.setEntryPort(entryPort);
    }

    public void requestService(Observer observer,Object iformation, int protocol) throws IOException{
        this.shipMessage(iformation, protocol);
        this.serviceResponseManager.addMessageListener(observer);
    }

    public void waitServiceResponse(){
        this.serviceResponseManager.waitServiceResponse();
    }
    
}
